<template>
  <el-container v-loading="loading">

    <el-row>
      <el-button
        icon="fa fa-fw fa-refresh"
        size="mini"
        type="info"
        @click="handleRefresh">
      </el-button>

      <div class="autocomplete-group">
        <span>配送人员查询：</span>
        <el-autocomplete
          v-model="constraintForm.text"
          :fetch-suggestions="querySearchAsync"
          placeholder="请选择配送人员"
          @select="handleSelect"
          clearable
          size="small">
          <template slot-scope="{ item }">
            <div>{{ item.nickname }}</div>
          </template>
          <el-button slot="append" icon="el-icon-search" @click="getData"></el-button>
        </el-autocomplete>
      </div>
    </el-row>

    <el-table
      @selection-change="handleSelectionChange"
      :data="tableData"
      tooltip-effect="dark"
      border
      :default-sort="{prop: 'date', order: 'descending'}"
      :row-class-name="tableRowClassName">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>

      <el-table-column
        prop="nickname"
        label="微信昵称">
      </el-table-column>

      <el-table-column
        prop="sex"
        label="性别"
        sortable>
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sex==1">男</el-tag>
          <el-tag v-if="scope.row.sex==2">女</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="level"
        label="性别"
        sortable>
        <template slot-scope="scope">
          <el-tag>{{scope.row.level}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="avatar_url"
        label="头像"
        show-overflow-tooltip>
        <template slot-scope="scope">
          <img :src="scope.row.avatar_url" class="logo-img">
        </template>
      </el-table-column>

      <el-table-column
        prop="price"
        label="余额">
        <template slot-scope="scope">
          <i class="fa fa-fw fa-rmb"></i>
          <span style="margin-left: 10px">{{ scope.row.price }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope" class="operate-column">

          <el-button
            circle
            icon="fa fa-fw el-icon-edit"
            size="mini"
            type="primary"
            title="编辑"
            @click="handleDataView(scope.$index, scope.row)">
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.currentPage"
      :page-sizes="pagination.pageSizes"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <!-- 提示 -->
    <el-dialog
      title="操作窗口"
      :visible.sync="dialogVisible"
      width="1000px">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" label-position="left"
               class="demo-ruleForm" size="small">

        <el-form-item label="类型">
          <el-radio v-model="ruleForm.type" label="1" border>跑腿</el-radio>
          <el-radio v-model="ruleForm.type" label="2" border>代驾</el-radio>
          <el-radio v-model="ruleForm.type" label="3" border>家政</el-radio>
        </el-form-item>

        <el-form-item label="保证金">
          <el-radio v-model="ruleForm.bond_id" :label="promiseTypeItem.id" border
                    v-for="promiseTypeItem in promiseTypeGroup" v-if="promiseTypeItem.type == ruleForm.type">
            {{promiseTypeItem.name}}
          </el-radio>
        </el-form-item>

        <el-form-item label="跑腿人员姓名">
          <el-input v-model="ruleForm.name" placeholder="请输入姓名"></el-input>
        </el-form-item>

        <el-form-item label="身份证号">
          <el-input v-model="ruleForm.identity" placeholder="请输入身份证"></el-input>
        </el-form-item>

        <el-form-item label="身份证正面">
          <el-upload
            name="card_front"
            class="avatar-uploader"
            :show-file-list="false"
            :http-request="fileUpload"
            :on-success="handleAvatarSuccess">
            <img v-if="ruleForm.card_front" :src="ruleForm.card_front" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="身份证反面">
          <el-upload
            name="card_back"
            class="avatar-uploader"
            :show-file-list="false"
            :http-request="fileUpload"
            :on-success="handleAvatarSuccess">
            <img v-if="ruleForm.card_back" :src="ruleForm.card_back" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="驾驶证" v-if="ruleForm.type == 2">
          <el-upload
            name="license_front"
            class="avatar-uploader"
            :show-file-list="false"
            :http-request="fileUpload"
            :on-success="handleAvatarSuccess">
            <img v-if="ruleForm.license_front" :src="ruleForm.license_front" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="健康证" v-if="ruleForm.type == 3">
          <el-upload
            name="license_front"
            class="avatar-uploader"
            :show-file-list="false"
            :http-request="fileUpload"
            :on-success="handleAvatarSuccess">
            <img v-if="ruleForm.license_front" :src="ruleForm.license_front" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="success" @click="submitForm('ruleForm')">保 存</el-button>
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

  </el-container>
</template>

<script>
  export default {
    mounted: function () {
      this.getUserLevel();
      this.getData();
      this.getPromiseList();
    },
    methods: {
      /**
       * 数据请求
       * */
      getData: function () {
        let _this = this;
        this.api.searchNotAuthorizationOfUser({
          page: this.pagination.currentPage,
          paginate: this.pagination.pageSize,
        }).then(function (res) {
          if (res.code == 1) {
            _this.tableData = res.data.data;
            _this.pagination.total = res.data.total;
          }
          _this.loading = false;
        }).catch(function (res) {
          throw new Error(res);
        });
      },
      /**
       * 获取正在使用保证金
       * */
      getPromiseList: function () {
        let _this = this;
        this.api.getPromiseList().then(function (res) {
          if (res.code == 1) {
            _this.promiseTypeGroup = res.data;
          }
        }).catch(function (res) {
          throw new Error(res);
        });
      },
      /**
       * 用户等级加载
       * */
      getUserLevel: function () {
        let _this = this;
        this.api.getUserLevelList().then(function (res) {
          if (res.code == 1) {
            _this.userLevelGroup = res.data.data;
          }
        }).catch(function (res) {
          throw new Error(res);
        });
      },
      /**
       * 分页数改变
       */
      handleSizeChange: function (pageSize) {
        this.pagination.pageSize = pageSize;
        this.getData();
      },
      /**
       * 当前页面改变
       * @param currentPage
       */
      handleCurrentChange: function (currentPage) {
        this.pagination.currentPage = currentPage;
        this.getData();
      },
      tableRowClassName({row, rowIndex}) {
        if (rowIndex === 1) {
          return 'warning-row'
        } else if (rowIndex === 3) {
          return 'success-row'
        }
        return ''
      },
      /**
       * 数据刷新
       */
      handleRefresh: function () {
        this.getData();
        this.$message({
          showClose: true,
          message: '刷新成功',
          type: 'success'
        });
      },
      /**
       * 表格选中状态记录
       * @param val
       */
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      /**
       * 条件数据检索
       */
      constraintSearchData: function () {
        this.getData();
        this.$message({
          showClose: true,
          message: '查询成功',
          type: 'success'
        });
      },
      /**
       * 远程数据加载
       */
      querySearchAsync(queryString, cb) {
        let _this = this;
        this.api.searchNotAuthorizationOfUser({name: queryString}).then(function (res) {
          if (res.code == '1') {
            cb(res.data.data);
          }
        }).catch(function (res) {
          throw new Error(res);
        });
      },
      /**
       * 搜索下拉选择
       * @param item
       */
      handleSelect(item) {
        this.constraintForm.text = item.nickname;
        this.constraintForm.id = item.id;
      },
      /**
       * 数据视图
       * */
      handleDataView: function (index, row) {
        this.currentDataIndex = index;
        this.dialogVisible = true;
        let defaultData = {
          uid: '',  	//用户id
          type: '1',  	//等同于保证金type：1，跑腿；2，代驾；3，家政；
          name: '',  	//跑腿人员姓名
          identity: '',  	//身份证号
          card_front: '',  	//身份证正面
          card_back: '',  	//身份证反面
          license_front: '', 	//文本选填代驾必选
          health_front: '',		//文本选填家政必选
          bond_id: '',  	//保证金id
        };
        this.ruleForm = defaultData;
      },
      /**
       * 数据提交
       * @param formName
       */
      submitForm(formName) {
        let _this = this;
        var attrs = this.$attrs;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            _this.ruleForm.uid = _this.tableData[_this.currentDataIndex].id;
            _this.api.runnerAuthorizationService(_this.ruleForm).then(function (res) {
              if (res.code == 1) {
                _this.getData();
                _this.dialogVisible = false;
                _this.$message({
                  showClose: true,
                  message: res.msg,
                  type: 'success',
                });
              } else {
                _this.$message({
                  showClose: true,
                  message: res.msg,
                  type: 'warning'
                });
              }
            }).catch(function (error) {
              throw new Error(error);
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      fileUpload: function (fileInfo) {
        let file = fileInfo.file;
        let _this = this;
        this.BaseUtils.fileToBase64(file).then(function (value) {
          _this.api.uploadFileToBase64({
            file: value
          }, 'runner').then(function (res) {
            if (res.code == 1) {
              eval('_this.ruleForm.' + fileInfo.filename + '="' + res.data + '"');
              _this.$message({
                showClose: true,
                message: res.msg,
                type: 'success'
              });
            } else {
              _this.$message({
                showClose: true,
                message: res.msg,
                type: 'warning'
              });
            }
          }).catch(function (error) {
            throw new Error(error);
          })
        }).catch(function (error) {
          throw new Error(error);
        })
      },
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
    },
    data() {
      return {
        loading: true,  // 页面加载
        tableData: [
          {
            id: '',                //类型：Number  必有字段  备注：用户id
            nickName: '',                //类型：String  必有字段  备注：微信昵称
            sex: '',                //类型：Number  必有字段  备注：1男，2女，''未知
            phone: '',                //类型：String  必有字段  备注：电话
            member_grade: '',                //类型：String  必有字段  备注：会员等级
            member_integral: '',                //类型：Number  必有字段  备注：会员积分
            price: '',                //类型：String  必有字段  备注：余额
            order_count: '',                //类型：Number  必有字段  备注：订单总数
            order_start_time: '',                //类型：Number  必有字段  备注：第一次下单
            order_end_time: ''                //类型：Number  必有字段  备注：最后一次下单
          },
        ],
        promiseTypeGroup: [
          {                //类型：Object  必有字段  备注：下同
            id: 61,                //类型：Number  必有字段  备注：无
            type: 1,                //类型：Number  必有字段  备注：保证金类型：1，跑腿；2，代驾；3，家政；
            promise_money: "100.00",                //类型：String  必有字段  备注：保证金金额
            name: "跑腿默认保证金1",                //类型：String  必有字段  备注：保证金名称
            des: "mock"                //类型：String  必有字段  备注：保证金描述
          },
        ],
        multipleSelection: [],
        pagination: {
          total: 5,
          currentPage: 1,
          pageSize: 10,
          pageSizes: [5, 10, 20, 25, 30, 50, 100],
        },
        dialogVisible: false,   // 弹框
        currentDataIndex: null,
        constraintForm: {
          text: '',    // 检索姓名，默认''
          id: '',    // 用户id，默认0
        },
        ruleForm: {
          uid: '',  	//用户id
          type: '1',  	//等同于保证金type：1，跑腿；2，代驾；3，家政；
          name: '',  	//跑腿人员姓名
          identity: '',  	//身份证号
          card_front: '',  	//身份证正面
          card_back: '',  	//身份证反面
          license_front: '', 	//文本选填代驾必选
          health_front: '',		//文本选填家政必选
          bond_id: '',  	//保证金id
        }
      }
    },
  }
</script>

<style scoped>
  .el-container {
    display: block;
  }

  .el-table, .el-row {
    width: 98% !important;
    margin: 15px auto;
  }

  .el-pagination {
    text-align: center;
    margin: 15px 0;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }

  .logo-img {
    width: 40px;
    height: 40px;
  }

  .el-date-picker {
    top: -3px;
    margin: 0 0 0 15px;
  }

  .autocomplete-group {
    display: inline-block;
    margin-left: 15px;
    font-size: 12px;
  }

  .el-form {
    width: 80%;
    margin: 15px 0 15px 30px;
  }

  /* 图片上传 */
  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    width: 178px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .logo-img {
    width: 40px;
    height: 40px;
  }
</style>
